﻿namespace TiaoTiaoCode.Modbuser
{
    internal class ModbusAddress
    {
        /// <summary>
        /// 站号
        /// </summary>
        public int Station { get; private set; }

        /// <summary>
        /// 地址
        /// </summary>
        public ushort Address { get; set; }

        /// <summary>
        /// 功能码
        /// </summary>
        public int Function { get; set; }

        /// <summary>
        /// 是否写功能
        /// </summary>
        public int WriteFunction { get; private set; }

        public ModbusAddress(string address, byte station, byte function)
        {
            Station = -1;
            WriteFunction = -1;
            Function = function;
            Station = station;
            Address = 0;

            Parse(address);
        }

        void Parse(string address)
        {
            if (address.IndexOf(';') < 0)
            {
                // 正常地址，功能码03
                Address = ushort.Parse(address);
            }
            else
            {
                // 带功能码的地址
                string[] list = address.Split(';');
                for (int i = 0; i < list.Length; i++)
                {
                    if (list[i][0] == 's' || list[i][0] == 'S')
                    {
                        // 站号信息
                        Station = byte.Parse(list[i].Substring(2));
                    }
                    else if (list[i][0] == 'x' || list[i][0] == 'X')
                    {
                        Function = byte.Parse(list[i].Substring(2));
                    }
                    else if (list[i].StartsWith("w=") || list[i].StartsWith("W="))
                    {
                        WriteFunction = byte.Parse(list[i].Substring(2));
                    }
                    else
                    {
                        Address = ushort.Parse(list[i]);
                    }
                }
            }
        }
    }
}
